import { PayloadAction, createSlice } from '@reduxjs/toolkit'
import { TProductData } from '../../types'

export type TProductCart = Pick<
	TProductData,
	'_id' | 'name' | 'pictures' | 'stock' | 'price' | 'discount'
> & {
	purchaseAmount: number
}

type TCartState = {
	products: TProductCart[] | null
}

const initialState: TCartState = {
	products: null,
}

export const cartSlice = createSlice({
	name: 'cart',
	initialState,
	reducers: {
		plusPurchaseAmount: (
			state,
			action: PayloadAction<Pick<TProductCart, '_id'>>
		) => {
			if (!state.products) return
			// Поиск продукта в корзине
			const selectedProduct = state.products.find(
				({ _id }) => _id === action.payload._id
			)
			// Если продукт уже есть в корзине, то увеличиваем его количество
			if (selectedProduct) {
				// Определяем текущее колисество продукта
				const productAmount = selectedProduct.purchaseAmount
				const maxAvaibleAmount = selectedProduct.stock
				state.products = [
					...state.products.filter(({ _id }) => _id !== action.payload._id),
					{
						...selectedProduct,
						purchaseAmount:
							productAmount < maxAvaibleAmount
								? productAmount + 1
								: productAmount,
					},
				]
			}
		},
		minusPurchaseAmount: (
			state,
			action: PayloadAction<Pick<TProductCart, '_id'>>
		) => {
			if (!state.products) return
			// Поиск продукта в корзине
			const selectedProduct = state.products.find(
				({ _id }) => _id === action.payload._id
			)
			// Если продукт уже есть в корзине, то уменьшаем его количество
			if (selectedProduct) {
				// Определяем текущее колисество продукта
				const productAmount = selectedProduct.purchaseAmount
				state.products = [
					...state.products.filter(({ _id }) => _id !== action.payload._id),
					{
						...selectedProduct,
						purchaseAmount: productAmount >= 1 ? productAmount - 1 : 0,
					},
				]
			}
		},
		addProduct: (state, action: PayloadAction<TProductCart>) => {
			if (state.products?.find(({ _id }) => _id === action.payload._id)) return
			const newProduct = { ...action.payload, purchaseAmount: 1 }
			state.products = state.products
				? [...state.products, newProduct]
				: [newProduct]
		},
		deleteProduct: (
			state,
			action: PayloadAction<Pick<TProductCart, '_id'>>
		) => {
			if (!state.products) return
			state.products = state.products?.filter(
				({ _id }) => _id !== action.payload._id
			)
			if (state.products.length === 0) state.products = null
		},
	},
})
